import axios from 'axios'
import Notification from 'ant-design-vue/es/notification'

const request = axios.create({
	baseURL: process.env.VUE_APP_API_BASE_URL,
	timeout: 6000,
	headers: {
		'Content-Type': 'application/json;charset=UTF-8',
	},
})

const notification = function (message, description) {
	return Notification.error({
		message: message ?? 'error',
		description: description ?? '',
	})
}

const errorHandler = (error) => {
	if (error.response) {
		const data = error.response.data
		const status = error.response.status
		// TODO:获取token
		if (status === 403) {
			notification('Forbidden', data.message)
		}
		if (status === 401 && !data.result?.isLogin) {
			notification('Unauthorized', 'Authorization verification failed')
			// TODO: 登出
		}
	}
	return Promise.reject(error)
}

// #FFFFFF 请求拦截
request.interceptors.request.use((config) => {
	// TODO: 获取token
	return config
}, errorHandler)

// #FFFFFF 响应拦截
request.interceptors.response.use((response) => {
	const res = response.data
	if (res.code !== 20000) {
		notification(res.message)
		return Promise.reject(res.message || 'error')
	} else {
		return res
	}
}, errorHandler)

export default request
